package com.global.emc.spring.web.servlet.tags;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.FrameworkServlet;

import com.global.emc.core.components.token.Token;
import com.global.emc.core.components.token.impl.RandomNumberTokenManager;

/**   
 *  
 * @Description:  [生成防重复提交token]   
 * @Author:       [Joly_Huang]   
 * @CreateDate:   [2014年1月30日 下午10:53:01]   
 * @UpdateUser:   [Joly_Huang]   
 * @UpdateDate:   [2014年1月30日 下午10:53:01]   
 * @UpdateRemark: [说明本次修改内容]  
 * @Version:      [v1.0] 
 *    
 */
public class TokenTag extends TagSupport {
	
	private static final long serialVersionUID = -7179723217019044298L;
	
	private static final String TOKENMANAGER = "resubmitTokenManager";
	private static final String SERVLET_NAME = "DispatcherServlet";
	private static final String TOKEN_UNIQUE_ID = "tokenUniqueId";
	
	protected String getTokenManager() {
		return TOKENMANAGER;
	}
	protected String getServletName(){
		return SERVLET_NAME;
	}
	protected String getTokenUniqueId(){
		return TOKEN_UNIQUE_ID;
	}
	
	@Override
	public int doStartTag() throws JspException {
		
		WebApplicationContext webApplicationContext = WebApplicationContextUtils
				.getWebApplicationContext(super.pageContext.getServletContext(), FrameworkServlet.class.getName() + ".CONTEXT."+getServletName());
		RandomNumberTokenManager randomNumberTokenManager = webApplicationContext.getBean(getTokenManager(), RandomNumberTokenManager.class);
		Token token = randomNumberTokenManager.createToken();
		super.pageContext.getSession().setAttribute(randomNumberTokenManager.getTokenName(), token);
		
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("<input type=\"hidden\" id=\"").append(getTokenUniqueId())
		.append("\" name=\"").append(getTokenUniqueId())
		.append("\" value=\"").append(token.getUniqueId()).append("\" />");
		
		try {
			pageContext.getOut().write(stringBuilder.toString());
		} catch (IOException e) {
			throw new JspException(e.getMessage());
		}
		
		return super.doStartTag();
	}

}
